package Dao.impl;

import Dao.studentDao;
import domain.solr;
import domain.student;
import domain.studentgroup;
import domain.twosolr;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import uilts.C3P0utils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class StudentDaoImpl implements studentDao {
    C3P0utils c3P0utils=new C3P0utils();

    @Override
    public student login(String sql, student stu) throws SQLException {

        QueryRunner queryRunner = new QueryRunner(c3P0utils.getDataSource());

        return queryRunner.query(sql, new BeanHandler<student>(student.class), stu.getS_user(), stu.getS_password());

    }



    @Override
    public List<student> findAll(String sql, List list) throws SQLException {
        /*查询出所有学生信息*/
        QueryRunner queryRunner = new QueryRunner(c3P0utils.getDataSource());
        List<student> query=new ArrayList<student>();
        Object[] objects = list.toArray();
        query = queryRunner.query(sql, new BeanListHandler<student>(student.class),objects);



        /*for循环遍历学生信息*/
        for(student stu:query){
            System.out.println(stu.getS_groupid());
            //想办法把stu里面的studengGroup对象的数据填充进去。
            studentgroup query1 = queryRunner.query("select * from studentgroup where s_groupid=?", new BeanHandler<studentgroup>(studentgroup.class), stu.getS_groupid());
            stu.setStudentgroup(query1);
        }
        return  query;
    }


//    查询权限

    @Override
    public List<solr> findSolr(String sql, String name) {
        QueryRunner queryRunner = new QueryRunner(c3P0utils.getDataSource());
        try {
            List<solr> query = queryRunner.query(sql, new BeanListHandler<solr>(solr.class), name);
            for (int i=0;i<query.size();i++){
                String sql2="SELECT t_name\n" +
                        "FROM solr s,solrlevel sl ,Twolevel t\n" +
                        "WHERE sl.t_id=t.t_id\n" +
                        "AND sl.s_id=s.`s_id`\n" +
                        "AND s_name=?\n" +
                        "AND r_id=(SELECT r_id FROM role WHERE r_name=\n" +
                        "(SELECT r_name\n" +
                        "FROM  student stu,role r,studentrole st\n" +
                        "WHERE stu.`s_id`=st.`s_id`\n" +
                        "AND r.`r_id`=st.`r_id`\n" +
                        "AND stu.`s_name`=?\n" +
                        ")\n" +
                        ")";
                List<twosolr> query1 = queryRunner.query(sql2, new BeanListHandler<twosolr>(twosolr.class), query.get(i).getS_name(), name);
                query.get(i).setTwosolr(query1);
            }
            return  query;
        } catch (SQLException e) {
            e.printStackTrace();
        }


        return null;
    }


}
